﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Odyssey.Controls;
using Odyssey.Controls.Classes;
using System.Windows.Controls.Primitives;
using WpfELearningAuthoringTool;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using ScormModel;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using mshtml;
using Bytescout.PDF2HTML;
using WPFFolderBrowser;
using System.IO.Compression;
namespace RibbonBarRegion
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class RibbonBarHeader : RibbonWindow
    {
        //bool ctrl = false;
        private IHTMLDocument2 doc;
        bool isdraging = false;
        ImsManifest imsManifest = new ImsManifest();
        XmlSerializer serializer = new XmlSerializer(typeof(ImsManifest));
        ManifestProcessing manifestProcessing = null;
        BinaryFormatter bf = new BinaryFormatter();
        ResourceUtil ru = new ResourceUtil();
        string currentPath = "D:/Courses/PPL";
        string courseTitle = "Default";
        string filename = null;
        TreeViewItem previousItem = null;
        public string CurrentPath
        {
            get { return this.currentPath; }
            set { this.currentPath = value; }
        }
        public string CourseTitle
        {
            get { return this.courseTitle; }
            set { this.courseTitle = value; }
        }
        public RibbonBarHeader()
        {
            InitializeComponent();
            SkinManager.SkinId = SkinId.OfficeBlack;
            setupBrowser();
            setUpFront();
            setUpFontSize();
            cbFontSize.SelectedValue = 3;
            this.Closing += new System.ComponentModel.CancelEventHandler(MainWindowClose);
            //  browser.Navigate("file:///D:/Test.html");
        }
        private void setupBrowser()
        {
            browser.NavigateToString("<html><HEAD><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'></HEAD><body></body></html>");
            browser.IsEnabled = false;
            doc = browser.Document as IHTMLDocument2;
            doc.defaultCharset = "UTF-8";
            doc.designMode = "On";
            // browser.ContextMenu += new HtmlElementEventHandler(Document_ContextMenuShowing);
        }
        //protected override void OnKeyDown(KeyEventArgs e)
        //{
        //    if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
        //        ctrl = true;
        //    if (ctrl && e.Key == Key.S)
        //    {
        //        saveResoureData();
        //    }
        //    base.OnKeyDown(e);

        //}

        //protected override void OnKeyUp(KeyEventArgs e)
        //{
        //  //  if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
        //        ctrl = false;

        //    base.OnKeyUp(e);
        //}
        private void setUpFront()
        {
            //  AutoCompleteStringCollection ac = new AutoCompleteStringCollection();
            foreach (FontFamily font in Fonts.SystemFontFamilies)
            {
                RibbonComboBoxItem item = new RibbonComboBoxItem();
                item.Content = font.ToString();
                item.Tag = font;
                cbFont.Items.Add(item);
            }

            //fontComboBox.Leave += new EventHandler(fontComboBox_TextChanged);
            //fontComboBox.AutoCompleteMode = AutoCompleteMode.Suggest;
            //fontComboBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
            //  fontComboBox.AutoCompleteCustomSource = ac;
        }
        private void setUpFontSize()
        {
            for (int x = 1; x <= 10; x++)
            {
                RibbonComboBoxItem item = new RibbonComboBoxItem();
                item.Content = x.ToString();
                item.Tag = x.ToString();
                cbFontSize.Items.Add(item);
            }
        }
        private void ExportClick(object sender, RoutedEventArgs e)
        {
            WPFFolderBrowserDialog dlg = new WPFFolderBrowserDialog();
            if (dlg.ShowDialog() == true)
            {
                string exportPath = dlg.FileName;
                exportPath = exportPath.Replace("\\", "/");
                string tempExport = exportPath;
                exportPath = exportPath + "/Result";
                if (Directory.Exists(exportPath))
                {
                    Directory.Delete(exportPath, true);
                    Directory.CreateDirectory(exportPath);
                }
                else
                    Directory.CreateDirectory(exportPath);
                try
                {
                    //load html
                    exportStatus.Text = "Process hmtl";
                    exportProcess.Value = 0;
                    for (int i = 0; i < imsManifest.Resources.ListResource.Count; i++)
                    {
                        Resource ri = imsManifest.Resources.ListResource[i];
                        for (int j = 0; j < ri.ListFileRef.Count; j++)
                        {
                            FileRef fi = ri.ListFileRef[j];
                            if (fi.Bref.Contains(".htm"))
                            {
                                //load html here
                                using (StreamReader reader = File.OpenText(currentPath + "/" + fi.Bref))
                                {
                                    string content = reader.ReadToEnd();
                                    //preprocess path for string
                                    ResourceUtil imageUtil = new ResourceUtil();
                                    List<string> list = imageUtil.FetchLinksFromSource(content);
                                    foreach (string m in list)
                                    {
                                        string iPath = m;
                                        if (iPath.Contains("htp://"))
                                            continue;
                                        string desName = System.IO.Path.GetFileName(m);
                                        string desPath = "Images/" + desName;
                                        content = content.Replace(m, desPath);
                                    }
                                    List<string> cssList = new List<string>();
                                    cssList = imageUtil.FetchCSSFromSource(content);
                                    if (cssList.Count > 0)
                                    {
                                        foreach (string cssi in cssList)
                                        {
                                            string cssPath = cssi;
                                            if (cssPath.Contains("htp://"))
                                                continue;
                                            string desCssName = System.IO.Path.GetFileName(cssPath);
                                            string desCssPath = "css/" + desCssName;
                                            content = content.Replace(cssi, desCssPath);
                                        }
                                    }
                                    List<string> javascriptList = new List<string>();
                                    javascriptList = imageUtil.FetchJavaScriptFromSource(content);
                                    if (javascriptList.Count > 0)
                                    {
                                        foreach (string jsi in javascriptList)
                                        {
                                            string jsPath = jsi;
                                            if (jsPath.Contains("htp://"))
                                                continue;
                                            string desJsName = System.IO.Path.GetFileName(jsPath);
                                            string desJsPath = "js/" + desJsName;
                                            content = content.Replace(jsi, desJsPath);
                                        }
                                    }

                                    using (StreamWriter writer = File.CreateText(exportPath + "/" + fi.Bref))
                                    {

                                        writer.Write(content);
                                        exportStatus.Text = "Process " + fi.Bref;
                                        writer.Close();
                                    }
                                }
                                break;
                            }
                            else
                                continue;
                        }
                    }
                    exportProcess.Value += 20;
                    //copy utils,css,media,js,image
                    exportStatus.Text = "Create resource directory";
                    if (!Directory.Exists(exportPath + "/Util"))
                    {
                        Directory.CreateDirectory(exportPath + "/Util");
                    }
                    if (!Directory.Exists(exportPath + "/Images"))
                    {
                        Directory.CreateDirectory(exportPath + "/Images");
                    }
                    if (!Directory.Exists(exportPath + "/css"))
                    {
                        Directory.CreateDirectory(exportPath + "/css");
                    }
                    if (!Directory.Exists(exportPath + "/js"))
                    {
                        Directory.CreateDirectory(exportPath + "/js");
                    }
                    if (!Directory.Exists(exportPath + "/media"))
                    {
                        Directory.CreateDirectory(exportPath + "/media");
                    }
                    exportProcess.Value += 20;
                    exportStatus.Text = "Copy resource directory";
                    string schemaPath = Directory.GetCurrentDirectory() + "\\Schema";
                    FileUtil.Copy(currentPath + "/Util", exportPath + "/Util");
                    FileUtil.Copy(currentPath + "/Images", exportPath + "/Images");
                    FileUtil.Copy(currentPath + "/css", exportPath + "/css");
                    FileUtil.Copy(currentPath + "/js", exportPath + "/js");
                    FileUtil.Copy(currentPath + "/media", exportPath + "/media");
                    FileUtil.Copy(schemaPath, exportPath);
                    exportProcess.Value += 20;
                    exportStatus.Text = "Create Manifest file";
                    TextWriter w = new StreamWriter(exportPath + "/imsmanifest.xml");
                    serializer.Serialize(w, imsManifest);
                    w.Close();
                    exportProcess.Value += 20;
                    exportStatus.Text = "Zip file!";

                    // zip file here
                    ICSharpCode.SharpZipLib.Zip.FastZip z = new ICSharpCode.SharpZipLib.Zip.FastZip();
                    z.CreateEmptyDirectories = true;
                    z.CreateZip(tempExport + "/course.zip", exportPath, true, "");
                    FileUtil.DirectoryDeleteAll(exportPath);
                    exportProcess.Value += 20;
                    exportStatus.Text = "Complete!";
                    MessageBox.Show("Export success");
                }
                catch (Exception e1)
                {
                    MessageBox.Show("Export fail");
                }

            }


        }
        private void ExportToHtmlClick(object sender, RoutedEventArgs e)
        {
            WPFFolderBrowserDialog dlg = new WPFFolderBrowserDialog();
            exportProcess.Value = 0;
            if (dlg.ShowDialog() == true)
            {
                string exportPath = dlg.FileName;
                exportPath = exportPath.Replace("\\", "/");
                //string tempExport = exportPath;
                //exportPath = exportPath + "/Result";
                if (Directory.Exists(exportPath))
                {
                    Directory.Delete(exportPath, true);
                    Directory.CreateDirectory(exportPath);
                }
                else
                    Directory.CreateDirectory(exportPath);
                try
                {
                    if (imsManifest != null)
                    {
                        HtmlExportUtil htmlExportUtil = new HtmlExportUtil();
                        ManifestProcessing mp = new ManifestProcessing(imsManifest);
                        htmlExportUtil.ListResourceItem = mp.findReourceItems();
                        htmlExportUtil.Imsmanifest = imsManifest;
                        using (StreamWriter writer = File.CreateText(exportPath + "/index.htm"))
                        {
                            writer.Write(htmlExportUtil.CreateHtmlNode().HTML);
                            writer.Close();
                        }
                        exportProcess.Value += 5;
                        for (int i = 0; i < imsManifest.Resources.ListResource.Count; i++)
                        {
                            Resource ri = imsManifest.Resources.ListResource[i];
                            exportProcess.Value += 2;
                            for (int j = 0; j < ri.ListFileRef.Count; j++)
                            {
                                FileRef fi = ri.ListFileRef[j];
                                if (fi.Bref.Contains(".htm"))
                                {
                                    //load html here
                                    using (StreamReader reader = File.OpenText(currentPath + "/" + fi.Bref))
                                    {
                                        string content = reader.ReadToEnd();
                                        //preprocess path for string
                                        ResourceUtil imageUtil = new ResourceUtil();
                                        List<string> list = imageUtil.FetchLinksFromSource(content);
                                        foreach (string m in list)
                                        {
                                            string iPath = m;
                                            if (iPath.Contains("htp://"))
                                                continue;
                                            string desName = System.IO.Path.GetFileName(m);
                                            string desPath = "Images/" + desName;
                                            content = content.Replace(m, desPath);
                                        }
                                        List<string> cssList = new List<string>();
                                        cssList = imageUtil.FetchCSSFromSource(content);
                                        if (cssList.Count > 0)
                                        {
                                            foreach (string cssi in cssList)
                                            {
                                                string cssPath = cssi;
                                                if (cssPath.Contains("htp://"))
                                                    continue;
                                                string desCssName = System.IO.Path.GetFileName(cssPath);
                                                string desCssPath = "css/" + desCssName;
                                                content = content.Replace(cssi, desCssPath);
                                            }
                                        }
                                        List<string> javascriptList = new List<string>();
                                        javascriptList = imageUtil.FetchJavaScriptFromSource(content);
                                        if (javascriptList.Count > 0)
                                        {
                                            foreach (string jsi in javascriptList)
                                            {
                                                string jsPath = jsi;
                                                if (jsPath.Contains("htp://"))
                                                    continue;
                                                string desJsName = System.IO.Path.GetFileName(jsPath);
                                                string desJsPath = "js/" + desJsName;
                                                content = content.Replace(jsi, desJsPath);
                                            }
                                        }

                                        using (StreamWriter writer = File.CreateText(exportPath + "/" + fi.Bref))
                                        {
                                            writer.Write(content);
                                            writer.Close();
                                        }
                                    }
                                    break;
                                }
                                else
                                    continue;

                            }
                        }
                        if (!Directory.Exists(exportPath + "/Util"))
                        {
                            Directory.CreateDirectory(exportPath + "/Util");
                        }
                        if (!Directory.Exists(exportPath + "/Images"))
                        {
                            Directory.CreateDirectory(exportPath + "/Images");
                        }
                        if (!Directory.Exists(exportPath + "/css"))
                        {
                            Directory.CreateDirectory(exportPath + "/css");
                        }
                        if (!Directory.Exists(exportPath + "/js"))
                        {
                            Directory.CreateDirectory(exportPath + "/js");
                        }
                        if (!Directory.Exists(exportPath + "/media"))
                        {
                            Directory.CreateDirectory(exportPath + "/media");
                        }
                        //copy file
                        FileUtil.Copy(currentPath + "/Util", exportPath + "/Util");
                        FileUtil.Copy(currentPath + "/Images", exportPath + "/Images");
                        FileUtil.Copy(currentPath + "/css", exportPath + "/css");
                        FileUtil.Copy(currentPath + "/js", exportPath + "/js");
                        FileUtil.Copy(currentPath + "/media", exportPath + "/media");
                        exportProcess.Value += 5;
                        try
                        {
                            File.Delete(exportPath + "/js/Photoshop_APIWrapper.js");
                        }
                        catch { }
                        exportProcess.Value = 100;
                        MessageBox.Show("Export Success");
                    }
                    else
                    {
                        MessageBox.Show("Please create course");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private void ExportToPDFClick(object sender, RoutedEventArgs e)
        {
            WPFFolderBrowserDialog dlg = new WPFFolderBrowserDialog();
            var documents = new List<EO.Pdf.PdfDocument>();
            if (dlg.ShowDialog() == true)
            {
                string exportPath = dlg.FileName;
                exportPath = exportPath.Replace("\\", "/");
                try
                {
                    if (imsManifest != null)
                    {
                        exportProcess.Value = 0;
                        for (int i = 0; i < imsManifest.Resources.ListResource.Count; i++)
                        {
                            Resource ri = imsManifest.Resources.ListResource[i];
                            for (int j = 0; j < ri.ListFileRef.Count; j++)
                            {
                                FileRef fi = ri.ListFileRef[j];
                                if (fi.Bref.Contains(".htm"))
                                {
                                    //load html here
                                    var doc = new EO.Pdf.PdfDocument();
                                    EO.Pdf.HtmlToPdf.ConvertUrl(currentPath + "/" + fi.Bref, doc);
                                    documents.Add(doc);
                                    exportProcess.Value += 3;
                                    using (StreamReader reader = File.OpenText(currentPath + "/" + fi.Bref))
                                        break;
                                }
                                else
                                    continue;
                            }
                        }
                        EO.Pdf.PdfDocument mergedDocument = EO.Pdf.PdfDocument.Merge(documents.ToArray());
                        mergedDocument.Save(exportPath + "/output.pdf");
                        exportProcess.Value = 100;
                        MessageBox.Show("Export to PDF Success");
                    }
                    else
                    {
                        MessageBox.Show("Please create course");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        #region Linear Template
        private void Win7Click(object sender, RoutedEventArgs e)
        {
            SkinManager.SkinId = SkinId.Windows7;
        }

        private void OfficeBlueClick(object sender, RoutedEventArgs e)
        {
            SkinManager.SkinId = SkinId.OfficeBlue;
        }

        private void OfficeSilverClick(object sender, RoutedEventArgs e)
        {
            SkinManager.SkinId = SkinId.OfficeSilver;
        }

        private void OfficeBlackClick(object sender, RoutedEventArgs e)
        {
            SkinManager.SkinId = SkinId.OfficeBlack;
        }

        private void Context1Click(object sender, RoutedEventArgs e)
        {
            ribbonBar.ContextualTabSet = ribbonBar.ContextualTabSets[0];
        }

        private void Context2Click(object sender, RoutedEventArgs e)
        {
            ribbonBar.ContextualTabSet = ribbonBar.ContextualTabSets[1];
        }

        private void ContextOffClick(object sender, RoutedEventArgs e)
        {
            ribbonBar.ContextualTabSet = null;
        }


        private void ShowBelowClick(object sender, RoutedEventArgs e)
        {
            ribbonBar.ToolbarPlacement = QAPlacement.Bottom;
        }

        private void ShowAboveClick(object sender, RoutedEventArgs e)
        {
            ribbonBar.ToolbarPlacement = QAPlacement.Top;
        }

        private void CloseDemoClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void RibbonGroup_LaunchDialog(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Launcher");
        }

        private void RibbonToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            window.IsGlassEnabled = true;

        }
        #endregion
        private bool checkValidItem()
        {
            if (tvMain.SelectedItem != null)
            {
                string title = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
                Item selectItem = manifestProcessing.findItem(title);
                if (selectItem == null)
                {
                    return false;
                }
                else
                {
                    if (selectItem.ListChildItem.Count > 0)
                        return false;
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        private void loadResource()
        {
            //      saveTempfile();
            string path = "";
            string title = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
            Item selectItem = manifestProcessing.findItem(title);
            if (selectItem != null)
            {
                if (selectItem.ListChildItem.Count > 0 || selectItem.ItemType == "MODULE" || selectItem.ItemType == "EXAM" || (selectItem.ItemType == "PRETEST" && imsManifest.TemplateCourse != "Competency") || selectItem.ItemType == "POSTTEST" || selectItem.ItemType == "LESSONS")
                {
                    browser.NavigateToString("<html><HEAD><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'></HEAD><body>Only leaf item can be edited</body></html>");
                    browser.IsEnabled = false;
                    return;
                }
                Resource selectResource = manifestProcessing.findResourceForItem(selectItem);
                if (selectResource != null)
                {

                    path = currentPath + "/" + selectResource.Bref;
                    if (File.Exists(path))
                    {
                        using (StreamReader reader = File.OpenText(path))
                        {
                            string content = reader.ReadToEnd();
                            browser.NavigateToString(content);
                            browser.IsEnabled = true;
                        }
                    }
                    else
                    {

                    }
                }
                else
                {
                    browser.NavigateToString("<html><HEAD><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'></HEAD><body>Add content here</body></html>");
                    browser.IsEnabled = true;
                }
            }
            else
            {
                browser.NavigateToString("<html><HEAD><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'><body>Only leaf item can be edited</body></html>");
                browser.IsEnabled = false;
            }
        }
        private bool checkNewResource()
        {
            bool result = false;
            string title = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
            Item selectItem = manifestProcessing.findItem(title);
            if (selectItem != null)
            {
                Resource selectResource = manifestProcessing.findResourceForItem(selectItem);
                if (selectResource != null)
                {

                    string path = currentPath + "/" + selectResource.Bref;
                    if (File.Exists(path))
                    {
                        result = false;
                    }
                }
                else
                {
                    result = true;
                }
            }
            else
            {
                result = false;
            }
            return result;
        }
        private bool checkNewResource(TreeViewItem selectedItem)
        {
            bool result = false;
            string title = manifestProcessing.getNameOfTreeViewItem(selectedItem);
            Item selectItem = manifestProcessing.findItem(title);
            if (selectItem != null)
            {
                Resource selectResource = manifestProcessing.findResourceForItem(selectItem);
                if (selectResource != null)
                {

                    string path = currentPath + "/" + selectResource.Bref;
                    if (File.Exists(path))
                    {
                        result = false;
                    }
                }
                else
                {
                    result = true;
                }
            }
            else
            {
                result = false;
            }
            return result;
        }
        private void ImportHtmlClick(object sender, RoutedEventArgs e)
        {
            if (checkValidItem() == false && tvMain.SelectedItem != null)
            {
                MessageBox.Show("Please select valid item to import resource (leaf item)");
                return;
            }
            else if (checkValidItem() == false && tvMain.SelectedItem == null)
            {
                MessageBox.Show("Learning content is empty");
                return;
            }
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".html";
                dlg.Filter = "HTML files (*.html;*.htm)|*.html;*.htm";
                exportStatus.Text = "Import hmtl";
                exportProcess.Value = 0;
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    // File.Copy(dlg.FileName, currentPath + "/" + dlg.SafeFileName, true);
                    string importDirectory = System.IO.Path.GetDirectoryName(dlg.FileName);
                    if (importDirectory.Contains("\\"))
                        importDirectory = importDirectory.Replace("\\", "/");
                    //need to copy all resource such as java script, image, css

                    using (StreamReader reader = File.OpenText(dlg.FileName))
                    {
                        string content = reader.ReadToEnd();
                        // copy image
                        ResourceUtil imageUtil = new ResourceUtil();
                        List<string> list = imageUtil.FetchLinksFromSource(content);
                        exportStatus.Text = "Process Image";
                        exportProcess.Value += 20;
                        foreach (string m in list)
                        {
                            string iPath = m;
                            if (iPath.Contains("./"))
                                iPath = iPath.Replace("./", "");
                            else if (iPath.Contains("htp://") || iPath.Contains("://"))
                                continue;
                            string srcPath = importDirectory + "/" + iPath;
                            string desName = System.IO.Path.GetFileName(srcPath);
                            string desPath = currentPath + "/images/" + desName;
                            if (!File.Exists(desPath))
                            {
                                File.Copy(srcPath, desPath, true);
                            }
                        }
                        //copy css
                        exportStatus.Text = "Process css";
                        exportProcess.Value += 20;
                        List<string> cssList = new List<string>();
                        cssList = imageUtil.FetchCSSFromSource(content);
                        if (cssList.Count > 0)
                        {
                            foreach (string cssi in cssList)
                            {
                                string cssPath = cssi;
                                if (cssPath.Contains("./"))
                                    cssPath = cssPath.Replace("./", "");
                                else if (cssPath.Contains("htp://") || cssPath.Contains("://"))
                                    continue;
                                string srcCssPath = importDirectory + "/" + cssPath;
                                string desCssName = System.IO.Path.GetFileName(cssPath);
                                string desCssPath = currentPath + "/css/" + desCssName;
                                if (!File.Exists(desCssPath))
                                {
                                    File.Copy(srcCssPath, desCssPath, true);
                                }
                            }
                        }
                        //copy java script
                        exportStatus.Text = "Process js";
                        exportProcess.Value += 20;
                        List<string> javascriptList = new List<string>();
                        javascriptList = imageUtil.FetchJavaScriptFromSource(content);
                        if (javascriptList.Count > 0)
                        {
                            foreach (string jsi in javascriptList)
                            {
                                string jsPath = jsi;
                                if (jsPath.Contains("./"))
                                    jsPath = jsPath.Replace("./", "");
                                else if (jsPath.Contains("htp://") || jsPath.Contains("://"))
                                    continue;
                                else if (jsPath.Contains(".//"))
                                    continue;
                                string srcJsPath = importDirectory + "/" + jsPath;
                                string desJsName = System.IO.Path.GetFileName(srcJsPath);
                                string desJsPath = currentPath + "/js/" + desJsName;
                                if (!File.Exists(desJsPath))
                                {
                                    File.Copy(srcJsPath, desJsPath, true);
                                }
                            }
                        }
                        reader.Close();
                    }
                    //change here
                    using (StreamReader reader = File.OpenText(dlg.FileName))
                    {
                        //preprocess path for string
                        exportStatus.Text = "Process Path";
                        exportProcess.Value += 20;
                        string content = reader.ReadToEnd();
                        ResourceUtil imageUtil = new ResourceUtil();
                        List<string> list = imageUtil.FetchLinksFromSource(content);
                        foreach (string m in list)
                        {
                            string iPath = m;
                            if (iPath.Contains("./"))
                                iPath = iPath.Replace("./", "");
                            else if (iPath.Contains("htp://"))
                                continue;
                            string srcPath = importDirectory + "/" + iPath;
                            string desName = System.IO.Path.GetFileName(srcPath);
                            string desPath = currentPath + "/Images/" + desName;
                            content = content.Replace(m, desPath);
                        }
                        List<string> cssList = new List<string>();
                        cssList = imageUtil.FetchCSSFromSource(content);
                        if (cssList.Count > 0)
                        {
                            foreach (string cssi in cssList)
                            {
                                string cssPath = cssi;
                                if (cssPath.Contains("./"))
                                    cssPath = cssPath.Replace("./", "");
                                else if (cssPath.Contains("htp://"))
                                    continue;
                                string srcCssPath = importDirectory + "/" + cssPath;
                                string desCssName = System.IO.Path.GetFileName(srcCssPath);
                                string desCssPath = currentPath + "/css/" + desCssName;
                                content = content.Replace(cssi, desCssPath);
                            }
                        }
                        List<string> javascriptList = new List<string>();
                        javascriptList = imageUtil.FetchJavaScriptFromSource(content);
                        if (javascriptList.Count > 0)
                        {
                            foreach (string jsi in javascriptList)
                            {
                                string jsPath = jsi;
                                if (jsPath.Contains("./"))
                                    jsPath = jsPath.Replace("./", "");
                                else if (jsPath.Contains("htp://"))
                                    continue;
                                string srcJsPath = importDirectory + "/" + jsPath;
                                string desJsName = System.IO.Path.GetFileName(srcJsPath);
                                string desJsPath = currentPath + "/js/" + desJsName;
                                content = content.Replace(jsi, desJsPath);
                            }
                        }
                        browser.NavigateToString(content);
                        exportStatus.Text = "Process Done";
                        exportProcess.Value += 20;
                        reader.Close();
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void NewCourse_Click(object sender, RoutedEventArgs e)
        {
            NewCourse newCourseDlg = new NewCourse();
            newCourseDlg.MainTree = tvMain;
            newCourseDlg.Imsmanifest = imsManifest;
            newCourseDlg.Owner = this;
            newCourseDlg.ParentChild = this;
            newCourseDlg.ShowDialog();
            manifestProcessing = new ManifestProcessing(imsManifest);
        }
        private void SaveCourse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string exportPath = currentPath + "\\" + courseTitle + ".dat";
                FileStream serializeStream = new FileStream(exportPath, FileMode.Create);
                bf.Serialize(serializeStream, imsManifest);
                serializeStream.Flush();
                serializeStream.Close();
                MessageBox.Show("Save successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void MainWindowClose(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (tvMain.SelectedItem != null)
            {
                MessageBoxResult result = MessageBox.Show("Do you want to save course ?", "E-Learning Tool", MessageBoxButton.YesNo,
           MessageBoxImage.Information, MessageBoxResult.Cancel);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        try
                        {
                            string exportPath = currentPath + "\\" + courseTitle + ".dat";
                            FileStream serializeStream = new FileStream(exportPath, FileMode.Create);
                            bf.Serialize(serializeStream, imsManifest);
                            serializeStream.Flush();
                            serializeStream.Close();
                        }
                        catch(Exception ex) {

                        }
                        break;
                    case MessageBoxResult.No:
                        break;
                }
            }
        }
        /*
         public bool TryClose()
{
    MessageBoxResult result = MessageBox.Show("Do you want to save changes?", appName, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);

   switch (result)
   {
       case MessageBoxResult.Yes:
           SaveAs();
           return false;
       case MessageBoxResult.No:
           this.Close();
           return false;
   }

   return true;
}
         */
        private void DeleteCourse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MessageBoxResult result = MessageBox.Show("Are you sure?", "E-Learning Tool", MessageBoxButton.YesNo,
        MessageBoxImage.Information, MessageBoxResult.Cancel);
                switch (result)
                {
                    case MessageBoxResult.Yes:

                        if (currentPath != "" && Directory.Exists(currentPath))
                        {
                            File.SetAttributes(currentPath, FileAttributes.Normal);
                            FileUtil.DirectoryDeleteAll(currentPath);
                            if (tvMain != null)
                                tvMain.Items.Clear();
                            MessageBox.Show("Delete Success");
                        }

                        break;
                    case MessageBoxResult.No:
                        this.Close();
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fail to delete all resource, some image files maybe in read only mode");
            }
        }
        private void saveTempfile()
        {
            string filename = currentPath + "/tempfile.htm";
            dynamic doc1 = browser.Document;

            var htmlText = doc1.documentElement.InnerHtml;
            using (StreamWriter writer = File.CreateText(filename))
            {
                writer.Write(htmlText);
                writer.Close();
            }
        }
        private void saveResoureData()
        {
            if (tvMain.SelectedItem == null)
            {
                MessageBox.Show("There is nothing to save");
                return;
            }
            else if( ((TreeViewItem)tvMain.SelectedItem).Items.Count > 0)
            {
                MessageBox.Show("Invalid item. Just leaf item has resource data");
                return;
            }
            try
            {
                string title1 = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
                Item selectItem1 = manifestProcessing.findItem(title1);
                if (selectItem1 != null && selectItem1.ItemType != "LESSON" && selectItem1.ItemType != "QUESTION" && selectItem1.ItemType != "TEST")
                    return;

                if (checkNewResource() == true)
                {
                    string id = DateTime.Now.Ticks.ToString();
                    string resourceTitle = "resoure" + id + ".htm";
                    string filename = currentPath + "/" + resourceTitle;
                    string title = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
                    Item selectItem = manifestProcessing.findItem(title);

                    Resource re = new Resource();
                    re.Identifier = "resource" + id;
                    re.Bref = resourceTitle;
                    if (selectItem.ItemType == "QUESTION" || selectItem.ItemType == "TEST")
                        re.ScormType = "sco";
                    else
                        re.ScormType = "asset";
                    re.Type = "webcontent";
                    FileRef fr = new FileRef();
                    fr.Bref = resourceTitle;
                    re.ListFileRef = new List<FileRef>();
                    re.ListFileRef.Add(fr);
                    manifestProcessing.addresource(re);

                    selectItem.Identifier = "item" + DateTime.Now.Ticks.ToString();
                    selectItem.Identifierref = re.Identifier;
                    dynamic doc = browser.Document;
                    doc.title = selectItem.Title;
                    var htmlText = doc.documentElement.InnerHtml;
                    htmlText = ru.processImagePath(htmlText, currentPath, re);
                    //   htmlText = ru.processCssPath(htmlText, currentPath, re);
                    //    htmlText = ru.processJavaScriptPath(htmlText, currentPath, re);
                 //   MessageBox.Show(filename);
                    using (StreamWriter writer = File.CreateText(filename))
                    {
                        if (!htmlText.Contains("<META content=text/html;charset=UTF-8 http-equiv=Content-Type>") || !htmlText.Contains("<meta content=text/html;charset=UTF-8 http-equiv=Content-Type>"))
                        {
                        if (htmlText.Contains("<HEAD>"))
                            htmlText = htmlText.Replace("<HEAD>", "<HEAD><META content=text/html;charset=UTF-8 http-equiv=Content-Type>");
                        else if (htmlText.Contains("<head>"))
                            htmlText = htmlText.Replace("<head>", "<head><META content=text/html;charset=UTF-8 http-equiv=Content-Type>");
                        }
                        writer.Write(htmlText);
                        writer.Close();
                    }
                }
                else
                {
                    string title = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
                    Item selectItem = manifestProcessing.findItem(title);
                    if (selectItem != null)
                    {
                        Resource selectResource = manifestProcessing.findResourceForItem(selectItem);
                        if (selectResource != null)
                        {
                            string path = currentPath + "/" + selectResource.Bref;
                            dynamic doc = browser.Document;
                            var htmlText = doc.documentElement.InnerHtml;
                            htmlText = ru.processImagePath(htmlText, currentPath, selectResource);
                            //       htmlText = ru.processCssPath(htmlText, currentPath, selectResource);
                            //       htmlText = ru.processJavaScriptPath(htmlText, currentPath, selectResource);
                            using (StreamWriter writer = File.CreateText(path))
                            {
                                if (!htmlText.Contains("<META content=text/html;charset=UTF-8 http-equiv=Content-Type>") || !htmlText.Contains("<meta content=text/html;charset=UTF-8 http-equiv=Content-Type>"))
                                {
                                    if (htmlText.Contains("<HEAD>"))
                                        htmlText = htmlText.Replace("<HEAD>", "<HEAD><META content=text/html;charset=UTF-8 http-equiv=Content-Type>");
                                    else if (htmlText.Contains("<head>"))
                                        htmlText = htmlText.Replace("<head>", "<head><META content=text/html;charset=UTF-8 http-equiv=Content-Type>");
                                }
                                writer.Write(htmlText);
                                writer.Close();
                            }
                        }
                    }
                }
                MessageBox.Show("Save resource successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void saveResoureDataAuto(TreeViewItem selectedItem)
        {

            if (selectedItem == null)
            {
                return;
            }
            else if (selectedItem.Items.Count > 0)
            {
                return;
            }
            string title1 = manifestProcessing.getNameOfTreeViewItem(selectedItem);
            Item selectItem1 = manifestProcessing.findItem(title1);
            if (selectItem1 != null && selectItem1.ItemType != "LESSON" && selectItem1.ItemType != "QUESTION" && selectItem1.ItemType != "TEST")
                return;
            try
            {
                if (checkNewResource(selectedItem) == true)
                {
                    string id = DateTime.Now.Ticks.ToString();
                    string resourceTitle = "resoure" + id + ".htm";
                    string filename = currentPath + "/" + resourceTitle;
                    string title = manifestProcessing.getNameOfTreeViewItem(selectedItem);
                    Item selectItem = manifestProcessing.findItem(title);

                    Resource re = new Resource();
                    re.Identifier = "resource" + id;
                    re.Bref = resourceTitle;
                    if (selectItem.ItemType == "QUESTION")
                        re.ScormType = "sco";
                    else
                        re.ScormType = "asset";
                    re.Type = "webcontent";
                    FileRef fr = new FileRef();
                    fr.Bref = resourceTitle;
                    re.ListFileRef = new List<FileRef>();
                    re.ListFileRef.Add(fr);
                    manifestProcessing.addresource(re);

                    selectItem.Identifier = "item" + DateTime.Now.Ticks.ToString();
                    selectItem.Identifierref = re.Identifier;
                    dynamic doc = browser.Document;
                    var htmlText = doc.documentElement.InnerHtml;
                    htmlText = ru.processImagePath(htmlText, currentPath, re);
                    //   htmlText = ru.processCssPath(htmlText, currentPath, re);
                    //    htmlText = ru.processJavaScriptPath(htmlText, currentPath, re);
                 //   MessageBox.Show(filename);
                    using (StreamWriter writer = File.CreateText(filename))
                    {
                        if (!htmlText.Contains("<META content=text/html;charset=UTF-8 http-equiv=Content-Type>") || !htmlText.Contains("<meta content=text/html;charset=UTF-8 http-equiv=Content-Type>"))
                        {
                            if (htmlText.Contains("<HEAD>"))
                                htmlText = htmlText.Replace("<HEAD>", "<HEAD><META content=text/html;charset=UTF-8 http-equiv=Content-Type>");
                            else if (htmlText.Contains("<head>"))
                                htmlText = htmlText.Replace("<head>", "<head><META content=text/html;charset=UTF-8 http-equiv=Content-Type>");
                        }
                        writer.Write(htmlText);
                        writer.Close();
                    }
                }
                else
                {
                    string title = manifestProcessing.getNameOfTreeViewItem(selectedItem);
                    Item selectItem = manifestProcessing.findItem(title);
                    if (selectItem != null)
                    {
                        Resource selectResource = manifestProcessing.findResourceForItem(selectItem);
                        if (selectResource != null)
                        {
                            string path = currentPath + "/" + selectResource.Bref;
                            dynamic doc = browser.Document;
                            var htmlText = doc.documentElement.InnerHtml;
                            htmlText = ru.processImagePath(htmlText, currentPath, selectResource);
                            //       htmlText = ru.processCssPath(htmlText, currentPath, selectResource);
                            //       htmlText = ru.processJavaScriptPath(htmlText, currentPath, selectResource);
                  //          MessageBox.Show(path);
                            using (StreamWriter writer = File.CreateText(path))
                            {
                                if (!htmlText.Contains("<META content=text/html;charset=UTF-8 http-equiv=Content-Type>") || !htmlText.Contains("<meta content=text/html;charset=UTF-8 http-equiv=Content-Type>"))
                                {
                                    if (htmlText.Contains("<HEAD>"))
                                        htmlText = htmlText.Replace("<HEAD>", "<HEAD><META content=text/html;charset=UTF-8 http-equiv=Content-Type>");
                                    else if (htmlText.Contains("<head>"))
                                        htmlText = htmlText.Replace("<head>", "<head><META content=text/html;charset=UTF-8 http-equiv=Content-Type>");
                                }
                                writer.Write(htmlText);
                                writer.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void SaveResource_Click(object sender, RoutedEventArgs e)
        {
            saveResoureData();
        }
        private void ClearTree_Click(object sender, RoutedEventArgs e)
        {
            if (tvMain != null)
                tvMain.Items.Clear();
        }
        private void Duplicate_Click(object sender, RoutedEventArgs e)
        {
            if (filename == null)
            {
                if (!SaveFileDialog())
                    return;
            }
            SaveFile(filename);
        }
        private void btnAboutClick(object sender, RoutedEventArgs e)
        {
            AboutDialog ad = new AboutDialog();
            ad.Owner = this;
            ad.ShowDialog();
        }
        private void LoadCourse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".dat";
                dlg.Filter = "Xml documents (.dat)|*.dat";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    // Open document
                    string loadPath = dlg.FileName;
                    currentPath = System.IO.Path.GetDirectoryName(loadPath);
                    if (currentPath.Contains("\\"))
                        currentPath = currentPath.Replace("\\", "/");
                    courseTitle = System.IO.Path.GetFileNameWithoutExtension(loadPath);
                    FileStream retrieveStream = new FileStream(loadPath, FileMode.Open);
                    imsManifest = new ImsManifest();
                    imsManifest = (ImsManifest)bf.Deserialize(retrieveStream);
                    imsManifest.xmlNameSpace = new XmlSerializerNamespaces();
                    imsManifest.xmlNameSpace.Add("", "");
                    imsManifest.xmlNameSpace.Add("", "http://www.imsglobal.org/xsd/imscp_v1p1");
                    imsManifest.xmlNameSpace.Add("adlcp", "http://www.adlnet.org/xsd/adlcp_v1p3");
                    imsManifest.xmlNameSpace.Add("adlseq", "http://www.adlnet.org/xsd/adlseq_v1p3");
                    imsManifest.xmlNameSpace.Add("imsss", "http://www.imsglobal.org/xsd/imsss");
                    imsManifest.xmlNameSpace.Add("adlnav", "http://www.adlnet.org/xsd/adlnav_v1p3");
                    imsManifest.xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                    imsManifest.SchemaLocation = "http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd http://www.adlnet.org/xsd/adlseq_v1p3 adlseq_v1p3.xsd http://www.imsglobal.org/xsd/imsss imsss_v1p0.xsd";
                    manifestProcessing = new ManifestProcessing(imsManifest);
                    TreeViewItem root = imsManifest.createManifestTreeViewItem();
                    tvMain.Items.Clear();
                    tvMain.Items.Add(root);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #region editor
        private void btnCut_Click(object sender, RoutedEventArgs e)
        {
            Cut();
        }
        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            Copy();
        }
        private void btnPaste_Click(object sender, RoutedEventArgs e)
        {
            Paste();
        }
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            Delete();
        }
        private void btnUndo_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("undo");
            Undo();
        }
        private void btnRedo_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("redo");
            Redo();
        }
        private void btnBold_Click(object sender, RoutedEventArgs e)
        {
            Bold();
        }
        private void btnItalic_Click(object sender, RoutedEventArgs e)
        {
            Italic();
        }
        private void btnUnderline_Click(object sender, RoutedEventArgs e)
        {
            Underline();
        }
        private void bntUnOrderList_Click(object sender, RoutedEventArgs e)
        {
            UnorderedList();
        }
        private void btnOrderList_Click(object sender, RoutedEventArgs e)
        {
            OrderedList();
        }
        private void btnIndent_Click(object sender, RoutedEventArgs e)
        {
            Indent();
        }
        private void btnOutdent_Click(object sender, RoutedEventArgs e)
        {
            Outdent();
        }
        private void btnAlignLeft_Click(object sender, RoutedEventArgs e)
        {
            JustifyLeft();
        }
        private void btnAlignCenter_Click(object sender, RoutedEventArgs e)
        {
            JustifyCenter();
        }
        private void btnAlignRight_Click(object sender, RoutedEventArgs e)
        {
            JustifyRight();
        }
        private void btnAlignJust_Click(object sender, RoutedEventArgs e)
        {
            JustifyFull();
        }
        private void btnInsertImage_Click(object sender, RoutedEventArgs e)
        {
            if (checkValidItem() == false && tvMain.SelectedItem != null)
            {
                MessageBox.Show("Please select valid item to import resource (leaf item)");
                return;
            }
            else if (checkValidItem() == false && tvMain.SelectedItem == null)
            {
                MessageBox.Show("Learning content is empty");
                return;
            }
            InsertImage();
        }
        private void btnFontColor_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Media.Color color = colorPicker();
            string colorstr =
                    string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("ForeColor", false, colorstr);
        }
        private void btnBackColor_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Media.Color color = colorPicker();
            string colorstr =
                    string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("BackColor", false, colorstr);
        }
        private void btnInsertBreak_Click(object sender, RoutedEventArgs e)
        {
            InsertBreak();
        }
        private void btnInsertParagraph_Click(object sender, RoutedEventArgs e)
        {
            InsertParagraph();
        }
        private bool DocCanUndo()
        {
            return doc.queryCommandEnabled("Undo");
        }
        private bool DocCanRedo()
        {
            return doc.queryCommandEnabled("Redo");
        }
        private bool DocCanCut()
        {
            return doc.queryCommandEnabled("Cut");
        }
        private bool DocCanCopy()
        {
            return doc.queryCommandEnabled("Copy");
        }
        private bool DocCanPaste()
        {
            return doc.queryCommandEnabled("Paste");
        }
        private bool DocCanDetete()
        {
            return doc.queryCommandEnabled("Delete");
        }
        public bool IsJustifyLeft()
        {
            return doc.queryCommandState("JustifyLeft");
        }

        public bool IsJustifyRight()
        {
            return doc.queryCommandState("JustifyRight");
        }


        public bool IsJustifyCenter()
        {
            return doc.queryCommandState("JustifyCenter");
        }


        public bool IsJustifyFull()
        {
            return doc.queryCommandState("JustifyFull");
        }


        public bool IsBold()
        {
            return doc.queryCommandState("Bold");
        }


        public bool IsItalic()
        {
            return doc.queryCommandState("Italic");
        }


        public bool IsUnderline()
        {
            return doc.queryCommandState("Underline");
        }


        public bool IsOrderedList()
        {
            return doc.queryCommandState("InsertOrderedList");
        }

        public bool IsUnorderedList()
        {
            return doc.queryCommandState("InsertUnorderedList");
        }

        public void Print()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            range.execCommand("Print", false, null);
            //browser.Document.ExecCommand("Print", true, null);
        }

        /// <summary>
        /// Insert a paragraph break
        /// </summary>
        public void InsertParagraph()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            range.execCommand("InsertParagraph", false, null);
        }

        /// <summary>
        /// Insert a horizontal rule
        /// </summary>
        public void InsertBreak()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            range.execCommand("InsertHorizontalRule", false, null);
        }

        /// <summary>
        /// Select all text in the document.
        /// </summary>
        public void SelectAll()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            range.execCommand("SelectAll", false, null);
        }

        /// <summary>
        /// Undo the last operation
        /// </summary>
        public void Undo()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
                range.execCommand("Undo", false, null);
            }
            catch
            {
                range = null;
            }
          
        }

        /// <summary>
        /// Redo based on the last Undo
        /// </summary>
        public void Redo()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
                range.execCommand("Redo", false, null);
            }
            catch
            {
                range = null;
            }
            
        }

        /// <summary>
        /// Cut the current selection and place it in the clipboard.
        /// </summary>
        public void Cut()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Cut", false, null);
        }

        /// <summary>
        /// Paste the contents of the clipboard into the current selection.
        /// </summary>
        public void Paste()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Paste", false, null);
        }

        /// <summary>
        /// Copy the current selection into the clipboard.
        /// </summary>
        public void Copy()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Copy", false, null);
        }

        /// <summary>
        /// Toggle the ordered list property for the current paragraph.
        /// </summary>
        public void OrderedList()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("InsertOrderedList", false, null);
        }

        /// <summary>
        /// Toggle the unordered list property for the current paragraph.
        /// </summary>
        public void UnorderedList()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("InsertUnorderedList", false, null);
        }

        /// <summary>
        /// Toggle the left justify property for the currnet block.
        /// </summary>
        public void JustifyLeft()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("JustifyLeft", false, null);
        }

        /// <summary>
        /// Toggle the right justify property for the current block.
        /// </summary>
        public void JustifyRight()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("JustifyRight", false, null);
        }

        /// <summary>
        /// Toggle the center justify property for the current block.
        /// </summary>
        public void JustifyCenter()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("JustifyCenter", false, null);
        }

        /// <summary>
        /// Toggle the full justify property for the current block.
        /// </summary>
        public void JustifyFull()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("JustifyFull", false, null);
        }

        /// <summary>
        /// Toggle bold formatting on the current selection.
        /// </summary>
        public void Bold()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Bold", false, null);
        }

        /// <summary>
        /// Toggle italic formatting on the current selection.
        /// </summary>
        public void Italic()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Italic", false, null);
        }

        /// <summary>
        /// Toggle underline formatting on the current selection.
        /// </summary>
        public void Underline()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Underline", false, null);
        }

        /// <summary>
        /// Delete the current selection.
        /// </summary>
        public void Delete()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Delete", false, null);
        }

        /// <summary>
        /// Insert an imange.
        /// </summary>
        public void InsertImage()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("InsertImage", true, null);
        }

        /// <summary>
        /// Indent the current paragraph.
        /// </summary>
        public void Indent()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Indent", false, null);
            else
                return;
        }

        /// <summary>
        /// Outdent the current paragraph.
        /// </summary>
        public void Outdent()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("Outdent", false, null);
            else
                return;
        }

        /// <summary>
        /// Insert a link at the current selection.
        /// </summary>
        /// <param name="url">The link url</param>
        public void InsertLink(string url)
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("CreateLink", false, url);
        }
        private System.Windows.Media.Color colorPicker()
        {
            System.Windows.Forms.ColorDialog colorDialog =
                       new System.Windows.Forms.ColorDialog();
            colorDialog.AllowFullOpen = true;
            colorDialog.ShowDialog();

            System.Windows.Media.Color col =
                                   new System.Windows.Media.Color();

            col.A = colorDialog.Color.A;
            col.B = colorDialog.Color.B;
            col.G = colorDialog.Color.G;
            col.R = colorDialog.Color.R;
            return col;
        }

        private void SelectFont_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("FontName", false, ((RibbonComboBoxItem)(cbFont.SelectedItem)).Content);
        }

        private void SelectFontSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document;
            IHTMLTxtRange range = null;
            try
            {
                if (doc.selection != null)
                    range = (IHTMLTxtRange)doc.selection.createRange();
            }
            catch
            {
                range = null;
            }
            if (range != null)
                range.execCommand("FontSize", false, ((RibbonComboBoxItem)(cbFontSize.SelectedItem)).Content);
        }
        private bool SaveFileDialog()
        {
            using (System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog())
            {
                dlg.AddExtension = true;
                dlg.DefaultExt = "htm";
                dlg.Filter = "HTML files (*.html;*.htm)|*.html;*.htm";
                System.Windows.Forms.DialogResult res = dlg.ShowDialog();
                if (res == System.Windows.Forms.DialogResult.OK)
                {
                    filename = dlg.FileName;
                    return true;
                }
                else
                    return false;
            }
        }

        private void SaveFile(string filename)
        {
            dynamic doc = browser.Document;
            var htmlText = doc.documentElement.InnerHtml;
            using (StreamWriter writer = File.CreateText(filename))
            {
                writer.Write(htmlText);
                writer.Close();
            }
        }
        private void insertFlash(string htnlText)
        {
            var element = doc.createElement("div");
            element.innerHTML = htnlText;
            doc.body.insertAdjacentHTML("afterBegin", element.outerHTML);
        }

        #endregion
        #region Insert Section
        private void btnInsertPDFClick(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".pdf";
                dlg.Filter = "Pdf files(.pdf)|*.pdf";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {

                    HTMLExtractor extractor = new HTMLExtractor();
                    extractor.RegistrationName = "demo";
                    extractor.RegistrationKey = "demo";

                    // Set HTML with CSS extraction mode
                    extractor.ExtractionMode = HTMLExtractionMode.HTMLWithCSS;

                    // Load sample PDF document
                    extractor.LoadDocumentFromFile(dlg.FileName);

                    // Convert 2-nd page to HTML and save it to file
                    extractor.SaveHtmlToFile("pdfHtml.html");
                    string htmlPdfPath = Directory.GetCurrentDirectory();
                    if (htmlPdfPath.Contains("\\"))
                        htmlPdfPath = htmlPdfPath.Replace("\\", "/");
                    string pdfHtml = preprocessPdfHtml(htmlPdfPath, "pdfHtml.html");
                    if (pdfHtml.Contains("(PDF to HTML SDK TRIAL VERSION)"))
                        pdfHtml = pdfHtml.Replace("(PDF to HTML SDK TRIAL VERSION)", "");
                    if (pdfHtml.Contains("(PRODUCED BY PDF to HTML SDK TRIAL VERSION)"))
                        pdfHtml = pdfHtml.Replace("(PRODUCED BY PDF to HTML SDK TRIAL VERSION)", "");
                    if (pdfHtml.Contains("(OUTPUT MADE BY PDF to HTML SDK 2.40.0.662)"))
                        pdfHtml = pdfHtml.Replace("(OUTPUT MADE BY PDF to HTML SDK 2.40.0.662)", "");
                    if (pdfHtml.Contains("(OUTPUT MADE BY PDF to HTML SDK TRIAL VERSION)"))
                        pdfHtml = pdfHtml.Replace("(OUTPUT MADE BY PDF to HTML SDK TRIAL VERSION)", "");
                    if (pdfHtml.Contains("(PRODUCED BY PDF to HTML SDK 2.40.0.662)"))
                        pdfHtml = pdfHtml.Replace("(PRODUCED BY PDF to HTML SDK 2.40.0.662)", "");
                    if (pdfHtml.Contains("(PRODUCED WITH PDF to HTML SDK 2.40.0.662)"))
                        pdfHtml = pdfHtml.Replace("(PRODUCED WITH PDF to HTML SDK 2.40.0.662)", "");
                    if (pdfHtml.Contains("(PRODUCED WITH PDF to HTML SDK TRIAL VERSION)"))
                        pdfHtml = pdfHtml.Replace("(PRODUCED WITH PDF to HTML SDK TRIAL VERSION)","");
                    browser.NavigateToString(pdfHtml);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private string preprocessPdfHtml(string path, string filename)
        {
            string pdfHtml = "";
            using (StreamReader reader = File.OpenText(path + "/" + filename))
            {
                string content = reader.ReadToEnd();
                // copy image
                ResourceUtil imageUtil = new ResourceUtil();
                List<string> list = imageUtil.FetchLinksFromSource(content);
                foreach (string m in list)
                {
                    string iPath = m;
                    if (iPath.Contains("./"))
                        iPath = iPath.Replace("./", "");
                    else if (iPath.Contains("htp://") || iPath.Contains("://"))
                        continue;
                    else if (iPath.Contains("\\"))
                        iPath = iPath.Replace("\\", "/");
                    string srcPath = path + "/" + iPath;
                    string desName = System.IO.Path.GetFileName(srcPath);
                    string desPath = currentPath + "/images/" + desName;
                    if (!File.Exists(desPath))
                    {
                        File.Copy(srcPath, desPath, true);
                    }
                }
                reader.Close();
            }
            using (StreamReader reader = File.OpenText(path + "/" + filename))
            {
                //preprocess path for string
                string content = reader.ReadToEnd();
                ResourceUtil imageUtil = new ResourceUtil();
                List<string> list = imageUtil.FetchLinksFromSource(content);
                foreach (string m in list)
                {
                    string iPath = m;
                    if (iPath.Contains("./"))
                        iPath = iPath.Replace("./", "");
                    else if (iPath.Contains("htp://"))
                        continue;
                    else if (iPath.Contains("\\"))
                        iPath = iPath.Replace("\\", "/");
                    string srcPath = path + "/" + iPath;
                    string desName = System.IO.Path.GetFileName(srcPath);
                    string desPath = currentPath + "/Images/" + desName;
                    content = content.Replace(m, desPath);
                }
                pdfHtml = content;
            }


            return pdfHtml;
        }
        private void btnInsertWordClick(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".doc";
                dlg.Filter = "Doc files(.doc)(.docx)|*.doc;*.docx";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    preProcessWordHtml(dlg.FileName);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void preProcessWordHtml(string path)
        {
            try
            {
                //Microsoft.Office.Interop.Word._Application newApp = new Microsoft.Office.Interop.Word.Application();
                //object TargetPath = @"D:/Test/test.html";

                //object Unknown = Type.Missing;
                //object Sourcepath = path;
                //Microsoft.Office.Interop.Word.Documents d = newApp.Documents;

                //Microsoft.Office.Interop.Word.Document od = d.Open(ref Sourcepath, ref Unknown,
                //         ref Unknown, ref Unknown, ref Unknown,
                //         ref Unknown, ref Unknown, ref Unknown,
                //         ref Unknown, ref Unknown, ref Unknown,
                //         ref Unknown, ref Unknown, ref Unknown, ref Unknown);
                //object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
                //newApp.ActiveDocument.SaveAs(ref TargetPath, ref format,
                //                            ref Unknown, ref Unknown, ref Unknown,
                //                            ref Unknown, ref Unknown, ref Unknown,
                //                            ref Unknown, ref Unknown, ref Unknown,
                //                            ref Unknown, ref Unknown, ref Unknown,
                //                            ref Unknown, ref Unknown);

                //newApp.Documents.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
                //newApp.Quit();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void btnInsertFlash_Click(object sender, RoutedEventArgs e)
        {
            if (checkValidItem() == false && tvMain.SelectedItem != null)
            {
                MessageBox.Show("Please select valid item to import resource (leaf item)");
                return;
            }
            else if (checkValidItem() == false && tvMain.SelectedItem == null)
            {
                MessageBox.Show("Learning content is empty");
                return;
            }
            string title = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
            Item selectItem = manifestProcessing.findItem(title);
            if (selectItem != null)
            {
                Resource selectResource = manifestProcessing.findResourceForItem(selectItem);
                if (selectResource != null)
                {
                    InsertFlashDialog flashDialog = new InsertFlashDialog();
                    flashDialog.Owner = this;
                    flashDialog.CurrentDirectory = currentPath;
                    flashDialog.DocManager = doc;
                    flashDialog.SelectResource = selectResource;
                    flashDialog.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Please save resource before insert flash");
                }
            }

        }
        private void btnInsertVideo_Click(object sender, RoutedEventArgs e)
        {
            if (checkValidItem() == false && tvMain.SelectedItem != null)
            {
                MessageBox.Show("Please select valid item to import resource (leaf item)");
                return;
            }
            else if (checkValidItem() == false && tvMain.SelectedItem == null)
            {
                MessageBox.Show("Learning content is empty");
                return;
            }
            string title = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
            Item selectItem = manifestProcessing.findItem(title);
            if (selectItem != null)
            {
                Resource selectResource = manifestProcessing.findResourceForItem(selectItem);
                if (selectResource != null)
                {
                    InsertVideoDialog videoDialog = new InsertVideoDialog();
                    videoDialog.Owner = this;
                    videoDialog.CurrentDirectory = currentPath;
                    videoDialog.DocManager = doc;
                    videoDialog.SelectResource = selectResource;
                    videoDialog.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Please save resource before insert video");
                }
            }
        }
        private void btnInsertAudio_Click(object sender, RoutedEventArgs e)
        {
            if (checkValidItem() == false && tvMain.SelectedItem != null)
            {
                MessageBox.Show("Please select valid item to import resource (leaf item)");
                return;
            }
            else if (checkValidItem() == false && tvMain.SelectedItem == null)
            {
                MessageBox.Show("Learning content is empty");
                return;
            }
            string title = manifestProcessing.getNameOfTreeViewItem((TreeViewItem)tvMain.SelectedItem);
            Item selectItem = manifestProcessing.findItem(title);
            if (selectItem != null)
            {
                Resource selectResource = manifestProcessing.findResourceForItem(selectItem);
                if (selectResource != null)
                {
                    InsertAudioDialog audioDialog = new InsertAudioDialog();
                    audioDialog.Owner = this;
                    audioDialog.CurrentDirectory = currentPath;
                    audioDialog.DocManager = doc;
                    audioDialog.SelectResource = selectResource;
                    audioDialog.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Please save resource before insert audio");
                }
            }
        }
        #endregion
        private void AddModule(object sender, ExecutedRoutedEventArgs e)
        {
            TreeViewItem temp = (TreeViewItem)tvMain.SelectedItem;
            TreeViewItem newNode = ScormModel.TreeUtil.GetTreeView("NewNode", "usa.png");
            temp.Items.Add(newNode);
        }


        /// <summary>
        /// Checks whether it is allowed to delete a category, which is only
        /// allowed for nested categories, but not the root items.
        /// </summary>
        private void EvaluateCanDelete(object sender, CanExecuteRoutedEventArgs e)
        {
            TreeViewItem temp = (TreeViewItem)tvMain.SelectedItem;
            try
            {
                TreeViewItem parent = (TreeViewItem)temp.Parent;
                if (parent != null)
                    e.CanExecute = true;
                else
                    e.CanExecute = false;
            }
            catch (Exception e1)
            {
                e.CanExecute = false;
            }

            e.Handled = true;
        }


        /// <summary>
        /// Deletes the currently processed item. This can be a right-clicked
        /// item (context menu) or the currently selected item, if the user
        /// pressed delete.
        /// </summary>
        private void DeleteCategory(object sender, ExecutedRoutedEventArgs e)
        {
            TreeViewItem temp = (TreeViewItem)tvMain.SelectedItem;
            TreeViewItem parent = (TreeViewItem)temp.Parent;
            parent.Items.Remove(temp);
        }

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = false;
            e.Handled = true;
        }

        private void tvMain_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (previousItem != null)
            {
                saveResoureDataAuto(previousItem);
            }
            TreeViewItem selectedItem = tvMain.SelectedItem as TreeViewItem;
            previousItem = selectedItem;
            Label setectItemLabel = null;
            StackPanel sp = null;
            //fix loi reload other template
            if (selectedItem != null)
            {
                loadResource();
                sp = (StackPanel)selectedItem.Header;
                foreach (var child in sp.Children)
                {
                    if (child.GetType().ToString() == "System.Windows.Controls.Label")
                        setectItemLabel = (Label)child;

                }
                ContextMenu contextMenu = new ContextMenu();
                string header = "";
                if (setectItemLabel != null)
                {
                    header = (setectItemLabel.Content).ToString();
                }
                if (selectedItem.Focus())
                {
                    if (selectedItem.Header == null)
                        return;
                    ManifestProcessing mp = new ManifestProcessing(imsManifest);
                    string typeOfItem = mp.findTypeOfItem(header);
                    ContextMenuUtils cmu = new ContextMenuUtils();
                    cmu.Imsmanifest = imsManifest;
                    cmu.MainTree = tvMain;
                    cmu.Container = ContentContainer;
                    cmu.Parent = this;
                    cmu.CurrentDirectory = currentPath;
                    cmu.WebBrowser = browser;
                    selectedItem.ContextMenu = cmu.buildContextMenuByTypeOfItem(typeOfItem, imsManifest.TemplateCourse);
                }
            }

        }

        private void tvMain_MouseMove(object sender, MouseEventArgs e)
        {
            if (!isdraging && e.LeftButton == MouseButtonState.Pressed)
            {
                isdraging = true;
                TreeViewItem tvi = tvMain.SelectedItem as TreeViewItem;
                if (tvi != null)
                {
                    if (tvi.Parent != null)
                    {
                        DragDrop.DoDragDrop(tvi.Parent, tvi, DragDropEffects.Move);
                    }
                    else
                    {
                        DragDrop.DoDragDrop(tvMain, tvi, DragDropEffects.Move);
                    }
                }
            }
        }

        private void tvMain_DragOver(object sender, DragEventArgs e)
        {
            if (isdraging)
            {
                if (e.Data != null)
                {
                    if (e.Data.GetDataPresent(typeof(TreeViewItem)))
                    {
                        e.Effects = DragDropEffects.Move;
                    }
                    else
                    {
                        e.Effects = DragDropEffects.None;
                    }
                }
            }

        }

        private void tvMain_Drop(object sender, DragEventArgs e)
        {
            //if (isdraging)
            //{
            //    if (e.Data != null)
            //    {
            //        TreeViewItem obj = e.Data.GetData(typeof(TreeViewItem)) as TreeViewItem;
            //        if (obj != null)
            //        {
            //            TreeViewItem treeViewItem = obj.Parent as TreeViewItem;

            //            if ((obj.Parent as TreeViewItem) != null)
            //            {
            //                (obj.Parent as TreeViewItem).Items.Remove(obj);
            //                treeViewItem.Items.Insert(0, obj);
            //            }
            //            e.Handled = true;
            //            isdraging = false;
            //        }
            //    }
            //}
        }

        private void SaveResourceData(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.S)
            {
                MessageBox.Show("user is pressed Ctrl+S");
            }
        }

        private void browser_LoadCompleted(object sender, NavigationEventArgs e)
        {
            
        }

        private void MoveItemToNext(object sender, RoutedEventArgs e)
        {
            if (tvMain.SelectedItem == null)
            {
                return;
            }
            if (manifestProcessing.SwapSelectedItemToNext((TreeViewItem)tvMain.SelectedItem) == true)
            {
                TreeViewProcessing tv = new TreeViewProcessing();
                tv.swapItemToNext((TreeViewItem)tvMain.SelectedItem);
               // ((TreeViewItem)tvMain.SelectedItem).Focus();
            }
        }
        private void MoveItemToPrevious(object sender, RoutedEventArgs e)
        {
            if (tvMain.SelectedItem == null)
            {
                return;
            }
            if (manifestProcessing.SwapSelectItemToPrevious((TreeViewItem)tvMain.SelectedItem) == true)
            {
                TreeViewProcessing tv = new TreeViewProcessing();
                tv.swapItemToPrevious((TreeViewItem)tvMain.SelectedItem);
                //((TreeViewItem)tvMain.SelectedItem).Focus();
            }
        }

        private void tvMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                e.Handled = true;
                return;
            }
        }

    }

}
